<template>
  <div
    :prop="prop"
    style="display:flex;"
  >
    <label for="bo-id">{{label}}</label>
    <slot
      id="bo-id"
      :errorStatus="errorStatus"
    ></slot>
    <p
      style="color:red;"
      v-if="errorStatus"
    >{{errorMsg}}</p>
  </div>
</template>

<script>
import Schema from 'async-validator';

export default {
  name: 'boFormItem',
  inject: ['boForm'],
  props: ['prop', 'label'],
  data() {
    return {
      errorMsg: '',
      errorStatus: false
    };
  },
  mounted() {
    this.$on('validate', this.validate);
  },
  methods: {
    validate(value) {
      const rules = this.boForm.rules[this.prop] || [];
      const option = { [this.prop]: rules };
      const schema = new Schema(option);
      schema.validate({ [this.prop]: value }, erros => {
        if (erros) {
          this.errorStatus = true;
          this.errorMsg = erros[0].message;
        } else {
          this.errorStatus = false;
          this.errorMsg = '';
        }
      });
    }
  }
};
</script>
